﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using KongMing.Project.Entity.Business;
using KongMing.Project.Entity.Common;
using KongMing.Project.Common;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using Newtonsoft.Json.Linq;
using KongMing.Project.IService.Business;
using Microsoft.Extensions.Options;
using KongMing.Project.Common.Sdk;
using KongMing.Project.IService.Common;
using KongMing.Project.Entity.Enum;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

namespace KongMing.Project.Service.Common
{
    public class AuthService : IAuthService
    {
        private BusinessDBContext _busdb;
        private JwtConfig _jwtConfig;
        private HttpContext _httpContext;
        public AuthService(IOptionsMonitor<JwtConfig> jwtConfig, IServiceProvider serviceProvider)
        {
            _jwtConfig = jwtConfig.CurrentValue;
            _busdb = serviceProvider.GetService<BusinessDBContext>();
            _httpContext = serviceProvider.GetService<IHttpContextAccessor>().HttpContext;
        }
        public async Task<BaseApiResult> LoginByAccountAndPwdAsync(string account, string pwd)
        {
            //登录验证
            if (string.IsNullOrWhiteSpace(account))
                throw new BusinessException("用户名不能为空！");
            var user = await _busdb.Queryable<SysUser>().Where(x => x.Account == account && x.Password == pwd).FirstAsync();
            if (user == null)
                throw new BusinessException("用户名或密码错误！");
            if (user.IsDelete == 1)
                throw new BusinessException("该用户已注销！");

            //创建Jwt令牌
            (string, int) AuthTokenAndType = JwtAuthTokenHelper.CreateJwtAuthToken(_jwtConfig, user);

            //保存登录信息到数据库
            SysAuthToken sysToken = new SysAuthToken();
            sysToken.LoginTime = Configs.NowTime;
            sysToken.Ip = _httpContext.Connection.RemoteIpAddress?.ToString();
            sysToken.UserId = user.UserId;
            sysToken.UserName = user.Name;
            sysToken.AuthToken = AuthTokenAndType.Item1;//生成的token
            sysToken.KeySymmetryType = AuthTokenAndType.Item2;//加密类型
            int res = await _busdb.Insertable(sysToken).ExecuteCommandAsync();

            return BaseApiResult.Success("登录成功", new { token = AuthTokenAndType.Item1 });
        }

        
    }
}
